package com.tally.server.service;

import com.tally.server.domain.${Domain};
import com.tally.server.domain.${Domain}Example;
import com.tally.server.dto.${Domain}DTO;
import com.tally.server.dto.PageDTO;
import com.tally.server.mapper.${Domain}Mapper;
import com.tally.server.utils.CopyUtil;
import com.tally.server.utils.UUIDUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
<#list typeSet as type>
    <#if type=='Date'>
import java.util.Date;
    </#if>
</#list>

@Service
public class ${Domain}Service {

    @Autowired
    private ${Domain}Mapper ${domain}Mapper;

    /**
     * 列表查询
     */
    public void list(PageDTO pageDTO) {
        PageHelper.startPage(pageDTO.getPage(), pageDTO.getSize());
        ${Domain}Example ${domain}Example = new ${Domain}Example();
        <#list fieldList as field>
            <#if field.nameHump=='sort'>
        ${domain}Example.setOrderByClause("sort asc");
            </#if>
        </#list>
        List<${Domain}> ${domain}List = ${domain}Mapper.selectByExample(${domain}Example);
        PageInfo<${Domain}> pageInfo = new PageInfo<>(${domain}List);
        pageDTO.setTotal(pageInfo.getTotal());
        List<${Domain}DTO> ${domain}DTOList = CopyUtil.copyList(${domain}List, ${Domain}DTO.class);
        pageDTO.setList(${domain}DTOList);
    }

    /**
     * 保存，id有值时更新，无值时新增
     */
    public void save(${Domain}DTO ${domain}DTO) {
        ${Domain} ${domain} = CopyUtil.copy(${domain}DTO, ${Domain}.class);
        if (StringUtils.isEmpty(${domain}DTO.getId())) {
            this.insert(${domain});
        } else {
            this.update(${domain});
        }
    }

    /**
     * 新增
     */
    private void insert(${Domain} ${domain}) {
        <#list typeSet as type>
            <#if type=='Date'>
        Date now = new Date();
            </#if>
        </#list>
        <#list fieldList as field>
            <#if field.nameHump=='createTime'>
        ${domain}.setCreateTime(now);
            </#if>
            <#if field.nameHump=='updateTime'>
        ${domain}.setUpdateTime(now);
            </#if>
        </#list>
        ${domain}.setId(UUIDUtil.getShortUUID());
        ${domain}Mapper.insert(${domain});
    }

    /**
     * 更新
     */
    private void update(${Domain} ${domain}) {
        <#list fieldList as field>
            <#if field.nameHump=='updateTime'>
        ${domain}.setUpdateTime(new Date());
            </#if>
        </#list>
        ${domain}Mapper.updateByPrimaryKey(${domain});
    }

    /**
     * 删除
     */
    public void delete(String id) {
        ${domain}Mapper.deleteByPrimaryKey(id);
    }
}
